<template>
  <div class="header">
    <div class="center" >
      <ul>
        <li class="logo" @click="$router.push({name:'homepage'})"><img src="./image/house.svg" alt="">佛山市小布村</li>
        <li v-for="item in menuList" @click="toPage(item.path)">{{ item.name }}</li>
      </ul>
      <div class="header-right">
        <div v-if="isLogin" class="loginAndRegister">
          <span @click="myLogin">登录 </span><el-divider direction="vertical"></el-divider> <span @click="myRegister"> 注册</span>
          <!--     登录对话框     -->
          <el-dialog
              title="登录"
              :visible.sync="loginDialogVisible"
              width="30%"
              :before-close="loginDialogClose"
              :modal-append-to-body="false"
              >
            <!--登录注册-->
            <div class="login">
              <el-tabs v-model="activeTab">
                <el-tab-pane label="用户端" name="user">
                  <el-form :model="userLoginForm" :rules="loginRules" ref="userLoginForm" label-width="60px" class="loginForm"
                           size="mini">
                    <el-form-item label="账号" prop="userPhone">
                      <el-input v-model="userLoginForm.userPhone"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="userPassword">
                      <el-input v-model="userLoginForm.userPassword" show-password></el-input>
                    </el-form-item>
                    <div class="btn">
                      <el-button type="primary" size="mini" @click="toUserBackground('userLoginForm')">登录</el-button>
                      <el-button size="mini" @click="toRegister">注册</el-button>
                    </div>
                  </el-form>
                </el-tab-pane>
                <el-tab-pane label="管理员端" name="adminer">
                  <el-form :model="adminLoginForm" :rules="loginRules" ref="adminLoginForm" label-width="60px" class="loginForm"
                           size="mini">
                    <el-form-item label="账号" prop="adminPhone">
                      <el-input v-model="adminLoginForm.adminPhone"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="adminPassword">
                      <el-input v-model="adminLoginForm.adminPassword" show-password></el-input>
                    </el-form-item>
                    <div class="btn">
                      <el-button type="primary" size="mini" @click="toAdminBackground('adminLoginForm')">登录</el-button>
                    </div>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </div>

          </el-dialog>
          <!--     注册对话框     -->
          <el-dialog
              title="新用户注册"
              :visible.sync="registerDialogVisible"
              width="40%"
              :before-close="registerDialogClose"
              :modal-append-to-body="false">
            <!--注册-->
            <div class="register">
              <el-form :model="registerForm" :rules="registerRules" ref="registerRules" label-width="80px"
                       class="registerForm"
                       size="mini">
                <el-form-item label="用户名" prop="userName">
                  <el-input v-model="registerForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="姓 名" prop="realName">
                  <el-input v-model="registerForm.realName"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="userPhone">
                  <el-input v-model="registerForm.userPhone"></el-input>
                </el-form-item>

                <el-form-item label="密 码" prop="userPassword">
                  <el-input v-model="registerForm.userPassword" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                  <el-input v-model="registerForm.checkPassword" show-password></el-input>
                </el-form-item>

                <el-form-item label="类型" prop="userType">
                  <el-radio-group v-model="registerForm.userType">
                    <el-radio label="1">游客</el-radio>
                    <el-radio label="0">村民</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="性别"  prop="userSex">
                  <el-radio-group v-model="registerForm.userSex">
                    <el-radio label="1">男</el-radio>
                    <el-radio label="0">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div class="btn registerBtn">
                  <el-button type="primary" size="mini" @click="register">注册</el-button>
                  <span><el-link type="success" @click="toLogin">已有帐号,立即登录!</el-link></span>
                </div>

              </el-form>
            </div>

          </el-dialog>
        </div>
        <el-dropdown v-if="!isLogin">
          <span class="el-dropdown-link" >
            <el-avatar :src="user.userAvatar" @click.native="toUserLayout" size="small"  @error="errorHandler">
              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
            </el-avatar>

          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="toUserLayout">个人中心</el-dropdown-item>
            <el-dropdown-item @click.native="userLogout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script>
import {getUserById, login, register, userLogin} from "@/api/allApi";
import {useUser} from "@/store/userStore";
import {validateContacts, validatePhone, validatePhone2} from "@/utils/validator";

export default {

  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.userPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      user: {},
      url: 'https://cdn.staticaly.com/gh/cf-01/image-hosting@master/images/main.308q9f6cxoi0.webp',
      User:useUser(),
      menuList: [
        {
          id: 0,
          name: '关于我们',
          path: '/userLayout/aboutUs'
        },
        {
          id: 1,
          name: '联系我们',
          path: '/userLayout/contactUs'
        },
        {
          id: 2,
          name: '反馈',
          path: '/userLayout/feedback'
        },
        {
          id: 3,
          name: '社区',
          path: '/userLayout/community'
        },
        {
          id: 4,
          name: '更多信息',
          path: '/userLayout/moreInformation'
        }
      ],
      /*登录部分*/
      isLogin: true,
      loginDialogVisible: false,
      registerDialogVisible: false,
      activeTab: 'user',
      adminLoginForm: {},
      userLoginForm: {},
      registerForm: {},
      loginRules: {
        adminPhone: [
          {required: true, message: '请输入用户名（手机号）', trigger: 'blur'},
          {validator:validatePhone2,  trigger: 'blur'},
        ],
        adminPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
        userPhone: [
          {required: true, message: '请输入账号（手机号）', trigger: 'blur'},
          {validator:validatePhone2,  trigger: 'blur'},
        ],
        userPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
      },
      registerRules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        userPhone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator:validatePhone,  trigger: 'blur'},

        ],
        userPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {
            pattern: /^(?![^a-zA-Z]+$)(?!\\D+$).{8,16}$/,
            message: "请输入包括数字和字母、长度8到16位的密码组合",
          },
        ],
        checkPassword: [
          {required: true,validator:validatePass2,  trigger: 'blur'},
        ],
        realName: [
          {required: true, message: '请输入用户真实姓名', trigger: 'blur'},
          {validator: validateContacts, trigger: 'blur'},
        ],
        userType: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        userSex: [
          {required: true, message: '请选择用户性别', trigger: 'change'},
        ],
      },
      registerType: '',
      registerGender: ''
    }
  },
  mounted() {
    if (JSON.parse(window.localStorage.getItem('access-user'))){
      this.user = JSON.parse(window.localStorage.getItem('access-user'))
      this.isLogin = this.User.isLogin
      this.loginDialogVisible = this.User.loginDialogVisible
    }else {
      this.isLogin = true
    }
    if (this.user.userId) {

      this.getUserByUserId()
    }
  },
  watch:{
    "User.loginDialogVisible" : function (){
      // console.log("触发了watch")
      this.loginDialogVisible = !this.loginDialogVisible
    },
    "User.changeUserAvatar" : function (){
      this.user = JSON.parse(window.localStorage.getItem('access-user'))
    }

  },
  methods: {
    myLogin() {
      // 点击打开登录对话框
      this.loginDialogVisible = true
    },
    errorHandler() {
      return true
    },
    myRegister() {
      // 点击跳转到用户注册对话框
      this.registerDialogVisible = true
    },
    register() {

      register(this.registerForm).then(res=>{
        if (res.data.success) {
          this.$message.success(res.data.data)
          this.registerDialogVisible = false
          this.registerForm = {}
        }
        else {
          this.$message.error(res.data.data)
        }
      })
    },
    // 登录对话框关闭回调函数
    loginDialogClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    // 用户注册对话框关闭回调函数
    registerDialogClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    getUserByUserId() {
      getUserById(this.user.userId).then(res=>{
        this.user = res.data.data
      })
    },
    toPage(path){
      this.$router.push({path:path})
    },
    toUserLayout() {
      this.$router.replace({path:'/userLayout/userBackground'})
    },
    toLogin() {
      this.loginDialogVisible=true
      this.registerDialogVisible=false
    },
    toRegister() {
      this.loginDialogVisible=false
      this.registerDialogVisible=true
    },
    toUserBackground(formName){

      this.$refs[formName].validate((valid) => {
        if (valid) {
          userLogin(this.userLoginForm).then(res=>{
            if (res.data.code === 200){
              window.localStorage.setItem('access-user',JSON.stringify(res.data))
              this.isLogin = this.User.isLogin
              this.$message.success(res.data.msg)
              this.User.url = res.data.userAvatar
              this.$router.replace({path:'/userLayout/userBackground'})
              this.loginDialogVisible = false
              this.userLoginForm = {}
            }
            else {
              this.$message.error(res.data.msg)
            }
          })
        } else {
          this.$message.error("用户名密码不能为空！")
          return false;
        }
      });

    },
    toAdminBackground(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.adminLoginForm).then(res=>{
            if (res.data.code === 200){
              window.localStorage.setItem('access-admin',JSON.stringify(res.data))
              this.$message.success(res.data.msg)
              this.$router.replace({path:'/adminLayout/adminBackground'})
              this.loginDialogVisible = false
              this.adminLoginForm = {}
            }
            else {
              this.$message.error(res.data.msg)
            }
          })
        } else {
          this.$message.error("用户名密码不能为空！")
          return false;
        }
      });


    },
    userLogout(){
      this.$router.push({path:'/'})
      //退出登陆，清空token
      localStorage.removeItem('access-user');
      this.$router.push({path:'/userLayout'})
      this.isLogin= true;
    }
  }
}
</script>

<style lang="less" scoped>
.header {

  width: 100%;
  height: 50px;

  font-size: 14px;
  border-bottom: solid 1px #cccccc;
  background-color: #fff;
  //background: #dce9e0 url(./image/head.png) no-repeat center top;

  .center {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100%;
    width: 80%;
    margin: auto;
    min-width: 900px;

    img {
      width: 25px;
      margin-right: 5px;
    }

    ul {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      li:hover {
        color: rgb(24, 144, 255);
      }

      li {
        list-style: none;
        color: #000;
        padding: 0 30px;
        //控制鼠标的样式
        cursor: pointer;
      }

      .logo {
        display: flex;
        align-items: center;
        padding: 0 30px 0 0;
      }
    }
  }

  .header-right {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .loginAndRegister {
      cursor: pointer;
    }

    .login {
      width: 100%;
    }
  }

  .loginForm,.register {
    width: 80%;
    margin: 30px auto;

    .btn {
      margin-top: 30px;
      padding-left: 50px;

    }
  }

  .registerBtn {
    display: flex;
    justify-content: space-between;
    padding-left: 60px;
  }


  /deep/ .el-dialog__body {
    padding: 0px 20px 30px 20px
  }

  /*/deep/ .el-dialog__header {
    padding: 0;
  }*/


.register {
  width: 80%;
}

}
</style>